package com.jh.paymentchannel.helipay.service;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.helipay.vo.SendPayCodeVo;
import com.jh.paymentchannel.helipay.vo.SendValidateCodeVo;
import com.jh.paymentchannel.service.SpendService;
import com.jh.paymentchannel.service.TopupRequest;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifu.DateTime;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.UUIDGenerator;
import net.sf.json.JSONObject;

@Service
public class HLTopupRequest implements TopupRequest{
private static final Logger log = LoggerFactory.getLogger(HLTopupRequest.class);
	
		@Autowired
		Util util;
		private String merchant_no = "C1800001614";
		@Autowired
	    SpendService ss;
	@Override
	public Map<String, String> topupRequest(HttpServletRequest request,
			String amount, String ordercode, String orderdesc, String extra,
			String notifyurl, String returnurl, String channelParam)
			throws Exception {
		if(null!=extra&&!"".equals(extra)) {
			Object rlt = ss.addordersonbyid(Long.valueOf(extra.trim()), ordercode);
			log.info("=========================="+Long.valueOf(extra.trim())+","+ordercode+"===========================");
			log.info("=========================="+rlt+"===========================");
		}
		Map map = new HashMap();
		RestTemplate restTemplate=new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/transactionclear/payment/query/ordercode--RESULT================"+result);
		JSONObject jsonObject =  JSONObject.fromObject(result);
		JSONObject resultObj  =  jsonObject.getJSONObject("result");
		String bankcard =  resultObj.getString("bankcard");
		String desc = resultObj.getString("desc");
		long userid = resultObj.getLong("userid");
		//String phone = resultObj.getString("phone");
		if(bankcard == null || bankcard.equalsIgnoreCase("")){
			map.put("resp_code", "999999");
			map.put("resp_message", "没有充值卡");
			return map;
		}
		
		String rt10_bindId = null;
		uri = util.getServiceUrl("paymentchannel", "error url request!");
		String road = uri.toString() + "/v1.0/paymentchannel/hlregister/findbycard";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("bankCard",bankcard);
		restTemplate=new RestTemplate();
		String resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
		log.info("接口/v1.0/paymentchannel/hlregister/findbycard--RESULT================"+resultObjx);
		jsonObject =  JSONObject.fromObject(resultObjx);
		JSONObject jsonobj = null;
		if(jsonObject.containsKey("result")) {
			jsonobj = jsonObject.getJSONObject("result");
		}else {
			map.put("resp_code", "failed");
			map.put(CommonConstants.RESP_MESSAGE, "没有绑卡数据");
			return map;
		}
		String phone = jsonobj.getString("phone");
		rt10_bindId = jsonobj.getString("bindId");
		String exemption = jsonobj.getString("exemption");
		String cardType = jsonobj.getString("cardType");
		if("2".equals(exemption)||("1".equals(exemption)&&"1".equals(cardType))) {
			/*绑卡支付*/
			RestTemplate restTemplate2=new RestTemplate();
			URI uri2 = util.getServiceUrl("paymentchannel", "error url request!");
			String url2 = uri2.toString() + "/v1.0/paymentchannel/topup/bindCardPay";
			requestEntity  = new LinkedMultiValueMap<String, String>();
			requestEntity.add("P1_bizType", "QuickPayBindPay");
			requestEntity.add("P2_customerNumber", merchant_no);
			requestEntity.add("P3_bindId", rt10_bindId);
			requestEntity.add("P4_userId", String.valueOf(userid));
			String reqTime = DateTime.getNow("yyyyMMddHHmmss");
			requestEntity.add("P5_orderId", ordercode);
			requestEntity.add("P6_timestamp", reqTime);
			requestEntity.add("P7_currency", "CNY");
			requestEntity.add("P8_orderAmount", amount);
			requestEntity.add("P9_goodsName", desc);
			requestEntity.add("P10_goodsDesc", "");
			requestEntity.add("P11_terminalType", "IMEI");
			requestEntity.add("P12_terminalId", "122121212121");
			requestEntity.add("P13_orderIp", request.getLocalAddr());
			requestEntity.add("P14_period", "");
			requestEntity.add("P15_periodUnit", "");
			requestEntity.add("P16_serverCallbackUrl", "http://47.104.158.3/v1.0/paymentchannel/topup/hl/notify_call");
			log.info("===================requestEntity=================="+requestEntity.toString());
			result = restTemplate2.postForObject(url2, requestEntity, String.class);
			log.info("===================result=================="+result.toString());
			JSONObject objs = JSONObject.fromObject(result);
			if("绑卡支付交易成功".equals(objs.getString("message"))) {
				map.put("resp_code", "success");
				map.put("type", "nourl");
				map.put("channel_type", "hl_pay");
			}else {
				map.put("resp_code", "failed");
				map.put(CommonConstants.RESP_MESSAGE, objs.getString("message"));
			}
			log.info("==============map=============="+map.toString());
			return map;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date();
        String time = sdf.format(date);
        Map mav = new HashMap();
        String obj = ss.findByBindId(rt10_bindId);
        log.info("==================="+obj+"===================");
        if(null!=obj&&!"".equals(obj)) {
        	Calendar c = Calendar.getInstance();
        	c.setTimeInMillis(sdf.parse(obj).getTime());
        	if((date.getTime()-c.getTimeInMillis())<300000) {
        		mav.put("resp_code", "failed");
        		int limitime = (int)(date.getTime()-c.getTimeInMillis())/60000;
        		if(limitime==0) {
        			limitime = (int)(date.getTime()-c.getTimeInMillis())/1000;
        			mav.put("message", "请在"+(60-limitime)+"秒后再次操作！");
        			return mav;
        		}
        		mav.put("message", "请在"+(5-limitime)+"分钟后再次操作！");
        		return mav;
        	}
        }
			String data;
			String reqTime = DateTime.getNow("yyyyMMddHHmmss");
			try {
				data = "?P2_customerNumber="+merchant_no+"&P3_bindId="+rt10_bindId
						+"&P4_userId="+userid+"&P5_orderId="+ordercode
						+"&P8_orderAmount="+"2.00"+"&P9_phone="+phone+"&P9_goodsName="+URLEncoder.encode(desc, "UTF-8")
						+"&P13_orderIp="+request.getLocalAddr()+"&reqTime="+reqTime
						+"&P16_serverCallbackUrl=http://47.104.158.3/v1.0/paymentchannel/topup/hl/notify_call";
				url = "http://47.104.158.3/v1.0/paymentchannel/topup/helipay"+data;
				map.put("resp_code", "success");
				map.put("channel_type", "hl_pay");
				map.put("url", url);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				log.info("======================"+e.getMessage()+"======================");
				map.put("resp_code", "failed");
				map.put("resp_message", e.getMessage());
			}
		return map; 
	
	}
}
